package text;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 * 1. 发送消息
 * 2. 接收消息
 */

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("启动服务器中>>...");
            socket=new Socket("localhost",8080);
            System.out.println("服务器启动成功>>...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        // 主线程 用于发送消息
        // 获取输出流

        try {
            Scanner scanner=new Scanner(System.in);
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw =new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);
            System.out.println("请输入昵称：");
            String nikeName=scanner.nextLine();
            while (nikeName.trim().isEmpty()){
                System.out.println("昵称不能为空，请重新输入：");
                nikeName=scanner.nextLine();
            }
            System.out.println("昵称设置成功,欢迎"+nikeName+"您，请开始聊天吧：");
            pw.println(nikeName);
            // 子线程 用于接收消息
            Runnable serverHandler=new ServerHandler();
            Thread t=new Thread(serverHandler);
            t.setDaemon(true);
            t.start();


            while (true){
                String message =scanner.nextLine();
                if (message.equals("exit")){
                    break;
                } else if (message.trim().isEmpty()){
                    System.out.println("消息不能为空，请重新输入：");
                    continue;
                }
                pw.println(message);

            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();//进行四次挥手告别
            }catch (IOException e){
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
    class ServerHandler implements Runnable{
        public void run() {
            try {
                InputStream is=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader bf=new BufferedReader(isr);
                String message;
                while ((message=bf.readLine())!=null){
                    System.out.println(message);
                }



            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
